package com.ikingtech.platform.service.job.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ikingtech.framework.sdk.enums.job.JobStatusEnum;
import com.ikingtech.framework.sdk.job.scheduler.JobScheduler;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.job.entity.JobDO;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tie yan
 */
@Service
@RequiredArgsConstructor
public class JobInitializer implements ApplicationRunner {

    private final JobService service;

    private final JobRepository repository;

    private final JobScheduler<JobDO> scheduler;

    @Override
    public void run(ApplicationArguments args) {
        List<JobDO> entities = this.repository.list(Wrappers.<JobDO>lambdaQuery().ne(JobDO::getStatus, JobStatusEnum.END.name()));
        if (Tools.Coll.isNotBlank(entities)) {
            this.scheduler.init(Tools.Coll.convertList(entities, this.service::createScheduledJob), this.service::feedback);
        } else {
            this.scheduler.init(new ArrayList<>(), this.service::feedback);
        }
    }
}
